/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mrp.persistencia.controller;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import mrp.beans.util.EntityManagerUtil;
import mrp.persistencia.controller.exceptions.NonexistentEntityException;
import mrp.persistencia.controller.exceptions.PreexistingEntityException;
import mrp.persistencia.controller.exceptions.RollbackFailureException;
import mrp.persistencia.entity.Tablaindice;

/**
 *
 * @author root
 */
public class TablaindiceJpaController implements Serializable {

    public TablaindiceJpaController() {
        this.emf = EntityManagerUtil.getEntityManagerFactory();
    }
    
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Tablaindice tablaindice) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(tablaindice);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findTablaindice(tablaindice.getCodtabla()) != null) {
                throw new PreexistingEntityException("Tablaindice " + tablaindice + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Tablaindice tablaindice) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            tablaindice = em.merge(tablaindice);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = tablaindice.getCodtabla();
                if (findTablaindice(id) == null) {
                    throw new NonexistentEntityException("The tablaindice with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            
            Tablaindice tablaindice;
            try {
                tablaindice = em.getReference(Tablaindice.class, id);
                tablaindice.getCodtabla();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The tablaindice with id " + id + " no longer exists.", enfe);
            }
            em.remove(tablaindice);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Tablaindice> findTablaindiceEntities() {
        return findTablaindiceEntities(true, -1, -1);
    }

    public List<Tablaindice> findTablaindiceEntities(int maxResults, int firstResult) {
        return findTablaindiceEntities(false, maxResults, firstResult);
    }

    private List<Tablaindice> findTablaindiceEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Tablaindice.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Tablaindice findTablaindice(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Tablaindice.class, id);
        } finally {
            em.close();
        }
    }

    public int getTablaindiceCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Tablaindice> rt = cq.from(Tablaindice.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    public String generaCodigo(String nombretabla,String sufijo)
    {
        ///////Metodo para obtener los primary Key que son Text de cada tabla y generar el siguiente, debido a que 
        ////// los primary key de la base de datos la mayoria son Text y son en secuencia numerica
        //////por lo que la tabla TablaIndice, almacena el último ID ingresado
        EntityManager em = null;
        em = getEntityManager();
        Tablaindice ti=null;
        try {
            Query q = em.createQuery("SELECT o FROM Tablaindice o where o.nombretabla = '"+nombretabla+"'");
            List l = q.getResultList();
            ti= (Tablaindice)l.get(0);            
            String codigo=this.creaNuevoCodigo(ti.getActualprimarykeytabla(), sufijo);
            
//            if(codigo.contains("-"))
//                codigo=codigo.substring(3);
//
//            try{
//                //System.out.println("codigo.substring ////// "+codigo);
//                int numero=Integer.parseInt(codigo.trim());
//                numero++;
//                codigo= sufijo.trim()+"-"+(""+numero).trim();            
//            }
//            catch(Exception e)
//            {
//                System.out.println("Error en metodo generarCodigo "+e);
//                codigo=null;
//                return null;
//            }
            return codigo;
        } 
        catch(Exception e)
        {e.printStackTrace();}
        finally {
            em.close();
        }
        return null;
    }
    public String creaNuevoCodigo(String codigoActual, String sufijo){
        String codigo=codigoActual;
            if(codigo.contains("-"))
                codigo=codigo.substring(3);

            try{
                //System.out.println("codigo.substring ////// "+codigo);
                int numero=Integer.parseInt(codigo.trim());
                numero++;
                codigo= sufijo.trim()+"-"+(""+numero).trim();     
                return codigo;
            }
            catch(Exception e)
            {
                System.out.println("Error en metodo creaNuevoCodigo "+e);
                codigo=null;
                return null;
            }
        
    }
}
